package com.pan.service.impl;

import com.pan.annotation.EntityNotNull;
import com.pan.dao.freight.FreightSelectDao;
import com.pan.dao.order1.OrderTable1Dao;
import com.pan.dao.order1.OrderTable1SelectDao;
import com.pan.dao.order2.OrderTable2SelectDao;
import com.pan.entity.Freight;
import com.pan.entity.OrderTable1;
import com.pan.entity.OrderTable2;
import com.pan.entity.Result;
import com.pan.enume.ResultEnum;
import com.pan.service.OrderSelectService;
import com.pan.tools.ConvertObject;
import com.pan.tools.RedisTools;
import com.pan.vo.ChildOrder;
import com.pan.vo.OrderVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service("orderSelectService")
public class OrderSelectServiceImpl implements OrderSelectService {


    @Resource
    private OrderTable1Dao orderTable1Dao;

    @Resource
    private OrderTable2SelectDao orderTable2SelectDao;
    @Resource
    private OrderTable1SelectDao orderTable1SelectDao;

    @Resource
    private FreightSelectDao freightSelectDao;
    @Resource
    private RedisTools redisTools;

    @Override
    public Result<List<OrderTable1> > selectByUserId(String userTicket){
        Long userId = Long.parseLong((String) redisTools.hget("user:"+userTicket,"id").getData());
        List<OrderTable1> li = orderTable1SelectDao.selectByUserId(userId);
        Result result = new Result<>(ResultEnum.SUCCESS);
        result.setData(li);
        return result;
    }

    @Override
    @EntityNotNull(daoClass = OrderTable2SelectDao.class,idName = "id")
    public Result selectById(Long id){
        OrderTable1 orderTable1 = orderTable1SelectDao.selectById(id);
        Result result = new Result(ResultEnum.SUCCESS,orderTable1);
        return result;
    }

    @Override
    @EntityNotNull(daoClass = OrderTable1SelectDao.class,idName = "order1Id")
    public Result<OrderVo> selectAllInfoById(Long order1Id){
        OrderTable1 order1 = orderTable1SelectDao.selectById(order1Id);
        if (order1 == null){
            return new Result(ResultEnum.NOT_FOUND_ERROR);
        }
        OrderVo orderVo = new OrderVo();
        orderVo = ConvertObject.copySameParameter(orderVo,order1);
        List<ChildOrder> childOrders = new ArrayList<>();
        List<OrderTable2> li = orderTable2SelectDao.selectByPid(order1Id);
        li.stream().forEach(order2->{
            Long freightId = order2.getFreightId();
            Freight freight = freightSelectDao.selectById(freightId);
            ChildOrder childOrder = ConvertObject.convertObject(new ChildOrder(),order2);
            childOrder.setFreight(freight);
            childOrders.add(childOrder);
        });
        orderVo.setChildOrders(childOrders);
        Result result = new Result(ResultEnum.SUCCESS);
        result.setData(orderVo);
        return result;
    }





}
